package jp.fsoriented.toishi;

import jp.fsoriented.toishi.data.AnmitsuData;
import jp.fsoriented.toishi.data.BibleConstant;
import jp.fsoriented.toishi.data.Verse;
import jp.fsoriented.toishi.util.L;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

/**
 * 入力・編集画面
 *
 * インテントフィルタ：jp.fsoriented.anmitsu.INPUT_VERSE ・・・連携による入力
 * エクストラ：入力・編集の区別、みことばの箇所など、またはデータのインデックス
 *
 * 入力：type=0, book, chapter, verse, content (必要に応じて to_chapter, to_verse)
 * 編集：type=1, index
 *
 * @author LapisCactus
 *
 */
public class InputActivity extends SherlockActivity {

	/** 選択ダイアログコード */
	private final static int REQUEST_BOOK = 0;
	/** 選択ダイアログコード */
	private final static int REQUEST_CHAPTER = 1;
	/** 選択ダイアログコード */
	private final static int REQUEST_VERSE = 2;
	/** 選択ダイアログコード */
	private final static int REQUEST_TO_CHAPTER = 3;
	/** 選択ダイアログコード */
	private final static int REQUEST_TO_VERSE = 4;

	/** int：0:入力画面、1:編集画面 */
	public final static String INTENT_EXTRA_TYPE = "type";
	/** int：書簡番号(0-65) */
	public final static String INTENT_EXTRA_BOOK = "book";
	/** int：章(1以上の整数) */
	public final static String INTENT_EXTRA_CHAPTER = "chapter";
	/** int：節(1以上の整数) */
	public final static String INTENT_EXTRA_VERSE = "verse";
	/** int：範囲 章(1以上の整数) */
	public final static String INTENT_EXTRA_TO_CHAPTER = "to_chapter";
	/** int：範囲 節(1以上の整数) */
	public final static String INTENT_EXTRA_TO_VERSE = "to_verse";
	/** String：みことば */
	public final static String INTENT_EXTRA_CONTENT = "content";
	/** int：インデックス */
	public final static String INTENT_EXTRA_INDEX = "index";

	/** 画面タイプ。0:入力画面、1:編集画面 */
	private int type;
	/** 編集中のみことば。編集中は位置を更新し、保存ボタン押下でヒントやみことばを詰めて、AnmitsuDataに入れる。 */
	private Verse verse;
	/** 編集中のみことばのインデックス。編集のみ有効。 */
	private int index;

	/**
	 * 入力画面を開始する
	 */
	public static final void startInputType(Context context) {
		Intent intent = new Intent();
		intent.setClass(context, InputActivity.class);
		intent.putExtra(INTENT_EXTRA_TYPE, 0);
		context.startActivity(intent);
	}

	/**
	 * 編集画面を開始する
	 */
	public static final void startEditType(Context context, int index) {
		Intent intent = new Intent();
		intent.setClass(context, InputActivity.class);
		intent.putExtra(INTENT_EXTRA_TYPE, 1);
		intent.putExtra(INTENT_EXTRA_INDEX, index);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_input);
		L.onCreate("Input");
		verse = new Verse();
		setLocationButtonText();
		// ActionBar設定
		ActionBar abar = getSupportActionBar();
		abar.setDisplayHomeAsUpEnabled(true);// onOptionsItemSelectedでR.id.homeがイベントで通知されるようになる
	}

	@Override
	protected void onResume() {
		super.onResume();
		L.onResume("Input");
		processIntent();
	}

	private void processIntent() {
		Intent intent = getIntent();
		L.d("processIntent" + intent);
		if (intent != null) {
			int type = intent.getIntExtra(INTENT_EXTRA_TYPE, 0);
			if (type == 1) {
				// 編集：インデックスが必須、そのほかは無視
				int index = intent.getIntExtra(INTENT_EXTRA_INDEX, -1);
				AnmitsuData data = AnmitsuData.getInstance();
				if ((index >= 0) && (index < data.verses.size())) {
					this.index = index;
					this.type = type;
					Verse v = data.verses.get(index);
					// AnmitsuDataからフィールドにコピーする
					verse.addedDate.setTime(v.addedDate.getTime());
					verse.content = v.content;
					verse.hint = v.hint;
					verse.okCount = v.okCount;
					verse.result.clear();
					verse.result.addAll(v.result);
					verse.position.set(v.position);
					if (v.isRange) {
						verse.toLocation.set(v.toLocation);
						verse.isRange = true;
					} else {
						verse.toLocation.set(0, 0, 0);
						verse.isRange = false;
					}
					// ビューに設定する
					updateViews();
				} else {
					// 不正なインデックスの場合は、画面を閉じる
					L.d("[input]intent:index ng. closing.");
					finish();
				}
			} else if (type == 0) {
				// 入力画面：直接指定のみ
				int posBook = intent.getIntExtra(INTENT_EXTRA_BOOK, -1);
				int posChapter = intent.getIntExtra(INTENT_EXTRA_CHAPTER, 0);
				int posVerse = intent.getIntExtra(INTENT_EXTRA_VERSE, 0);
				int posToChapter = intent.getIntExtra(INTENT_EXTRA_TO_CHAPTER, 0);
				int posToVerse = intent.getIntExtra(INTENT_EXTRA_TO_VERSE, 0);
				String content = intent.getStringExtra(INTENT_EXTRA_CONTENT);
				if ((posBook != -1) && (posChapter != 0) && (posVerse != 0) && (content != null)) {
					this.type = type;
					verse.position.book = posBook;
					verse.position.chapter = posChapter - 1;
					verse.position.verse = posVerse - 1;
					if (posToChapter != 0 && posToVerse != 0) {
						verse.toLocation.set(0, posToChapter - 1, posToVerse - 1);
						verse.isRange = true;
					} else {
						verse.toLocation.set(0, 0, 0);
						verse.isRange = false;
					}
					verse.content = content;
					// ビューに設定する
					updateViews();
					isExternalIntent = true;
				} else {
					// 空の入力画面とする

				}
			} else {
				L.d("[input]intent:type ng. closing.");
				finish();
			}
			setIntent(null);
		}
	}

	/** 外部からのインテントで起動した */
	private boolean isExternalIntent = false;

	private void updateViews() {
		// ビューに設定する
		TextView text;
		CheckBox check;
		Button btn;
		text = (TextView) findViewById(R.id.activity_input_edit_scripture);
		text.setText(verse.content);
		text = (TextView) findViewById(R.id.activity_input_edit_hint);
		text.setText(verse.hint);
		setTitle(R.string.input_actionbar_title_edit);
		setLocationButtonText();
		check = (CheckBox) findViewById(R.id.activity_input_check_use_range);
		check.setChecked(verse.isRange);
		btn = (Button) findViewById(R.id.activity_input_btn_tochapter);
		btn.setEnabled(verse.isRange);
		btn = (Button) findViewById(R.id.activity_input_btn_toverse);
		btn.setEnabled(verse.isRange);
	}

	/**
	 * みことばの箇所・範囲をあらわすボタンのテキストを設定する
	 *
	 * @param v
	 */
	private void setLocationButtonText() {
		Button btn;
		btn = (Button) findViewById(R.id.activity_input_btn_book);
		btn.setText(BibleConstant.getBookName(verse.position.book));
		btn = (Button) findViewById(R.id.activity_input_btn_chapter);
		btn.setText((verse.position.chapter + 1) + "章");
		btn = (Button) findViewById(R.id.activity_input_btn_verse);
		btn.setText((verse.position.verse + 1) + "節");
		btn = (Button) findViewById(R.id.activity_input_btn_tochapter);
		btn.setText((verse.toLocation.chapter + 1) + "章");
		btn = (Button) findViewById(R.id.activity_input_btn_toverse);
		btn.setText((verse.toLocation.verse + 1) + "節");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null) {
			return;
		}
		int which = data.getIntExtra(ItemSelectDialog.INTENT_RESULT_WHICH, 0);
		L.d("which" + which);
		switch (requestCode) {
		case REQUEST_BOOK:
			L.d("[input]book");
			verse.position.book = which;
			verse.position.chapter = 0;
			verse.position.verse = 0;
			verse.toLocation.chapter = 0;
			verse.toLocation.verse = 0;
			break;
		case REQUEST_CHAPTER:
			L.d("[input]chapter");
			verse.position.chapter = which;
			verse.position.verse = 0;
			break;
		case REQUEST_VERSE:
			L.d("[input]verse");
			verse.position.verse = which;
			break;
		case REQUEST_TO_CHAPTER:
			L.d("[input]to chapter");
			verse.toLocation.chapter = which;
			verse.toLocation.verse = 0;
			break;
		case REQUEST_TO_VERSE:
			L.d("[input]to verse");
			verse.toLocation.verse = which;
			break;
		}
		setLocationButtonText();
	}

	public void onChooseBookClick(View v) {
		ItemSelectDialog.start(this, ItemSelectDialog.MODE_BOOK, 0, verse.position.book, REQUEST_BOOK);
	}

	public void onChooseChapterClick(View v) {
		ItemSelectDialog.start(this, ItemSelectDialog.MODE_CHAPTER, BibleConstant.getChapterCount(verse.position.book),
				verse.position.chapter, REQUEST_CHAPTER);
	}

	public void onChooseVerseClick(View v) {
		ItemSelectDialog.start(this, ItemSelectDialog.MODE_VERSE,
				BibleConstant.getVerseCount(verse.position.book, verse.position.chapter), verse.position.verse,
				REQUEST_VERSE);
	}

	public void onChooseToChapterClick(View v) {
		ItemSelectDialog.start(this, ItemSelectDialog.MODE_CHAPTER, BibleConstant.getChapterCount(verse.position.book),
				verse.toLocation.chapter, REQUEST_TO_CHAPTER);
	}

	public void onChooseToVerseClick(View v) {
		ItemSelectDialog.start(this, ItemSelectDialog.MODE_VERSE,
				BibleConstant.getVerseCount(verse.position.book, verse.toLocation.chapter), verse.toLocation.verse,
				REQUEST_TO_VERSE);
	}

	public void onEnableRangeClick(View v) {
		CheckBox chk = (CheckBox) findViewById(R.id.activity_input_check_use_range);
		Button toChapterBtn = (Button) findViewById(R.id.activity_input_btn_tochapter);
		Button toVerseBtn = (Button) findViewById(R.id.activity_input_btn_toverse);
		boolean checked = chk.isChecked();
		L.d("[input]range " + checked);
		toChapterBtn.setEnabled(checked);
		toVerseBtn.setEnabled(checked);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_input, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.menu_input_actionbar_ok:
			// 保存ボタン
			L.d("OK selected.");
			AnmitsuData data = AnmitsuData.getInstance();
			data.load(this);
			verse.addedDate.setTime(System.currentTimeMillis());
			verse.hint = getStringFromEditText(R.id.activity_input_edit_hint);
			verse.content = getStringFromEditText(R.id.activity_input_edit_scripture);
			CheckBox check = (CheckBox) findViewById(R.id.activity_input_check_use_range);
			if (check.isChecked()) {
				verse.isRange = true;
			} else {
				verse.toLocation.set(0, 0, 0);
				verse.isRange = false;
			}
			verse.normalize();
			if (type == 0) {
				data.verses.add(verse);
			} else if (type == 1) {
				data.verses.set(index, verse);
			}
			data.markModified();
			data.store(this);
			finish();
			break;
		case android.R.id.home:
			// UPナビゲーション
			L.d("Back selected.");
			finish();
			if (isExternalIntent) {
				Intent intent = new Intent();
				intent.setClass(this, MainActivity.class);
				startActivity(intent);
			}
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private String getStringFromEditText(int id) {
		EditText view = (EditText) findViewById(id);
		if (view != null) {
			return view.getText().toString();
		} else {
			return null;
		}
	}
}
